<template>
  <div class="main-box">
    <div class="table-box">
      <div class="card mb10 pt0 pb0">
        <SelectFilter :data="selectFilterData" :default-values="selectFilterValues" @change="changeSelectFilter" />
      </div>
      <ProTable
        ref="proTable"
        title="订单列表"
        highlight-current-row
        :columns="columns"
        :request-api="getOrderList"
        :init-param="Object.assign(initParams, selectFilterValues)"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button type="primary" :icon="DocumentChecked" @click="openDrawerAddOrder()">新增订单</el-button>
          <el-button type="primary" :icon="Upload" plain @click="batchAdd">批量订购</el-button>
          <el-button type="primary" :icon="Download" plain @click="downloadFile">导出订单</el-button>
        </template>
        <!-- 单选 -->
        <template #radio="scope">
          <el-radio :label="scope.row.id" v-model="radio"><i></i></el-radio>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
          <el-button type="primary" link :icon="Refresh" @click="exchangeGoods(scope.row)">换货</el-button>
          <el-button type="primary" link :icon="RefreshRight" @click="returnGoods(scope.row)">退货</el-button>
        </template>
      </ProTable>
      <AddDrawer ref="drawerRefAdd" />
      <OrderDrawer ref="drawerRef" />
      <ImportExcel ref="dialogRef" />
    </div>
  </div>
</template>
<script setup lang="tsx" name="useSelectFilter">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import SelectFilter from "@/components/SelectFilter/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { Download, View, DocumentChecked, Upload, Refresh, RefreshRight } from "@element-plus/icons-vue";
import { BatchAddOrder, exportOrderInfo, getOrderList, showOrder, exchangeOrder, returnOrder } from "@/api/modules/custom";
import OrderDrawer from "./components/OrderDrawer.vue";
import AddDrawer from "./components/AddDrawer.vue";
import { useHandleData } from "@/hooks/useHandleData";
import { Custom } from "@/api/interface";
import { orderType, orderStatus } from "@/utils/serviceDict";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 单选
const radio = ref("");

// 表格配置项
const columns: ColumnProps[] = [
  { prop: "orderId", label: "订单id", width: 120, sortable: true, search: { el: "input" } },
  { prop: "orderType", label: "订单类型", width: 120, sortable: true, enum: orderType, tag: true },
  { prop: "customerId", label: "客户id", width: 120, search: { el: "input" } },
  {
    prop: "orderItems",
    render: scope => {
      return (
        <div>
          <text>{scope.row!.orderItems?.[0].goodsName}</text>
        </div>
      );
    },
    label: "商品名称",
    width: 160
  },
  {
    prop: "orderItems",
    render: scope => {
      return (
        <div>
          <text>{scope.row!.orderItems?.[0].goodsPrice}</text>
        </div>
      );
    },
    label: "商品价格",
    width: 120
  },
  {
    prop: "orderItems",
    render: scope => {
      return (
        <div>
          <text>{scope.row!.orderItems?.[0].count}</text>
        </div>
      );
    },
    label: "数量"
  },
  {
    prop: "orderItems",
    render: scope => {
      return (
        <div>
          <text>{scope.row!.orderItems?.[0].measureUnit}</text>
        </div>
      );
    },
    label: "计量单位"
  },
  { prop: "orderStatus", label: "订单状态", width: 120, sortable: true, enum: orderStatus, tag: true },
  { prop: "totalAmount", label: "总额" },
  { prop: "orderRemark", label: "备注" },
  { prop: "receiverName", label: "收货人名", width: 80 },
  { prop: "receiverPhone", label: "收货人电话", width: 120 },
  { prop: "expDeliveryTime", label: "期望配送时间", width: 120 },
  { prop: "createTime", label: "创建时间", width: 120 },
  { prop: "operation", label: "操作", width: 250, fixed: "right" }
];

// selectFilter 数据
const selectFilterData = reactive([
  {
    title: "订单类型(单)",
    key: "orderType",
    options: [
      {
        label: "全部",
        value: -1
      },
      {
        label: "配送单",
        value: 1,
        icon: "Box"
      },
      {
        label: "退货单",
        value: 2,
        icon: "SoldOut"
      },
      {
        label: "换货单",
        value: 3,
        icon: "Refresh"
      }
    ]
  },
  {
    title: "订单状态(多)",
    key: "orderStatus",
    multiple: true,
    options: [
      {
        label: "全部",
        value: -1
      },
      {
        label: "新建",
        value: 0,
        icon: "Tickets"
      },
      {
        label: "缺货",
        value: 1,
        icon: "Box"
      },
      {
        label: "待调度",
        value: 2,
        icon: "Sell"
      },
      {
        label: "待出库",
        value: 3,
        icon: "MessageBox"
      },
      {
        label: "运输中",
        value: 4,
        icon: "Van"
      },
      {
        label: "到达分站",
        value: 5,
        icon: "House"
      },
      {
        label: "派送中",
        value: 6,
        icon: "Van"
      },
      {
        label: "已完成",
        value: 7,
        icon: "CircleCheck"
      },
      {
        label: "已退货",
        value: 8,
        icon: "CircleCheck"
      },
      {
        label: "已换货",
        value: 9,
        icon: "CircleCheck"
      }
    ]
  }
]);

// 初始化方法，挂载之后执行的东西填到里面
onMounted(() => {});

const initParams = reactive({});

// 默认 selectFilter 参数
const selectFilterValues = ref({ orderType: -1, orderStatus: [-1] });
const changeSelectFilter = (value: typeof selectFilterValues.value) => {
  ElMessage.success("筛选成功 🤔");
  proTable.value!.pageable.current = 1;
  selectFilterValues.value = value;
};

// 导出任务单列表
const downloadFile = async () => {};

// 新订
const drawerRefAdd = ref<InstanceType<typeof AddDrawer> | null>(null);
const openDrawerAddOrder = () => {
  const params = {
    getTableList: proTable.value?.getTableList
  };
  drawerRefAdd.value?.acceptParams(params);
};

// 查看
const drawerRef = ref<InstanceType<typeof OrderDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Custom.ResOrderList> = {}) => {
  const params = {
    title,
    isView: title === "订货",
    row: { ...row },
    api: title === "查看" ? showOrder : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 换货
const exchangeGoods = async (params: Custom.ResOrderList) => {
  if (params.orderStatus === 7 && params.orderType === 1) {
    await useHandleData(exchangeOrder, { orderId: params.orderId }, `换货【${params.orderItems?.[0].goodsName}】`);
    proTable.value?.getTableList();
  } else {
    ElMessage.error("只有订单状态为已完成时才可以进行换货");
  }
};

// 退货
const returnGoods = async (params: Custom.ResOrderList) => {
  if (params.orderStatus === 7 && params.orderType === 1) {
    await useHandleData(returnOrder, { orderId: params.orderId }, `退订【${params.orderItems?.[0].goodsName}】`);
    proTable.value?.getTableList();
  } else {
    // 弹出窗口显示错误信息
    ElMessage.error("只有订单状态为已完成时才可以进行换货");
  }
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "订单",
    tempApi: exportOrderInfo,
    importApi: BatchAddOrder,
    getTableList: proTable.value?.getTableList
  };
  dialogRef.value?.acceptParams(params);
};
</script>
